<template>
  <!--动态表单容器-->
  <div class="dynamic-form-container"
       v-loading="!table.column.length"
       :element-loading-text="'加载中'"
       :element-loading-spinner="'el-icon-loading'"
       :element-loading-background="'rgba(0, 0, 0, 0)'"
       :class="{ 'vab-fullscreen': isFullscreen }">
    <!--搜索部分-->
    <div class="search-container">
      <el-form
        v-show="search.show"
        ref="searchForm"
        size="small"
        :model="search.data"
        inline>
        <el-form-item
          label="创建人"
          prop="create_by">
          <el-input v-model="search.data['create_by']" placeholder="请输入创建人"></el-input>
        </el-form-item>
        <template
          v-for="(item,index) in searchList">
          <el-form-item
            v-show="item.hide"
            :label="item.hideLabel ?'':item.label"
            :label-width="item.hideLabel ? '0': item.labelWidth+'px'"
            :key="'searchList'+index"
            :prop="item.prop">
            <!--            <component-->
            <!--              :form="search"-->
            <!--              :item="item"-->
            <!--              :is="'xl-' + item.type"-->
            <!--              :ref="'pluginChild' + item.type"-->
            <!--              :key="'search_component_item.' + index"-->
            <!--              :dictionary="dict"/>-->
            <!--拉下选择查询使用模糊查询-->
            <component
              :form="search"
              :key="'search_component_item.' + index"
              :is="'xl-' + (item.type === 'select' ? 'Input' : item.type)"
              :ref="'pluginChild' + item.type" :item="item"
              :dictionary="dict"/>
          </el-form-item>
        </template>
        <el-form-item>
          <el-button
            icon="el-icon-search"
            type="primary"
            @click="searchFormList">搜索
          </el-button>
        </el-form-item>
        <!--        <el-form-item>-->
        <!--          <el-dropdown-->
        <!--            size="small"-->
        <!--            @command="advancedQueriesCommand"-->
        <!--            split-button-->
        <!--            type="primary"-->
        <!--            @click="advancedQueries.visible = true">-->
        <!--            高级查询-->
        <!--            <el-dropdown-menu-->
        <!--              :style="{opacity: advancedQueries.list.length}"-->
        <!--              slot="dropdown">-->
        <!--              <el-dropdown-item-->
        <!--                v-for="(option, optionIndex) in advancedQueries.list"-->
        <!--                :key="'advancedQueries.list.' + optionIndex"-->
        <!--                :command="option.id">-->
        <!--                {{ option['queryName'] }}-->
        <!--              </el-dropdown-item>-->
        <!--            </el-dropdown-menu>-->
        <!--          </el-dropdown>-->
        <!--        </el-form-item>-->
        <el-form-item>
          <el-button
            icon="el-icon-refresh"
            @click="resetSearch">重置
          </el-button>
          <el-button type="text" @click="search.fold = !search.fold">
            <span v-if="search.fold">展开</span>
            <span v-else>收起</span>
            <!--            <vab-icon
                          class="vab-dropdown"
                          :class="{ 'vab-dropdown-active': search.fold }"
                          icon="arrow-up-s-line"/>-->
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!--导航栏部分-->
    <div class="nav-container">
      <el-form inline>
        <template v-for="(item, index) in navbar.list">
          <el-form-item
            v-has-perm="[formData.tableName + '_' + item.permissions]"
            :key="'navbar.list.' + formData.code + index">
            <el-button
              size="mini"
              :key="'navbar.list.' + index"
              type="primary"
              :disabled="item.disabled"
              @click="handleDynamicButton(item)">
              <!--              <vab-icon :icon="item.icon | filterIcon"/>-->
              <span v-show="item.isShowName">{{ item.name }}</span>
            </el-button>
          </el-form-item>
        </template>
        <el-form-item style="float: right; margin-right: 0;">
          <right-toolbar
            :info="formData"
            @trialCalc="trialClick"
            :isTrialCalc="Number(formData.isComputed) !== 0"
            :isFullscreen.sync="isFullscreen"
            :showSearch.sync="search.show"
            @queryTable="getFormList"/>
        </el-form-item>
        <el-form-item style="float: right; margin-right: 20px;">
          <el-pagination
            style="margin: 0;"
            @size-change="handleSizeChange"
            @current-change="getFormList"
            :current-page.sync="table.current"
            :page-size="table.size"
            :page-sizes="[10, 50, 100, 500]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="table.total">
          </el-pagination>
        </el-form-item>
      </el-form>
    </div>

    <!--表单列表部分-->
    <div
      class="table-container"
      :style="{height: tableHeight, opacity: table.column.length ? 1 : 0}">
      <vxe-table
        border
        stripe
        row-id="id"
        height="auto"
        ref="multipleTable"
        @checkbox-all="selectAllEvent"
        @checkbox-change="selectChangeEvent"
        v-loading="table.loading"
        :column-config="{resizable: true, isCurrent: true, isHover: true}"
        :row-config="{isHover: true, isCurrent: true, isHover: true}"
        :checkbox-config="{labelField: 'create_by', highlight: true, range: true}"
        :data="table.list">
        <vxe-column
          fixed="left"
          type="seq"
          width="60"/>
        <vxe-column
          show-overflow
          fixed="left"
          type="checkbox"
          title="创建人"
          field="create_by"
          width="100"/>
        <vxe-column
          min-width="200"
          show-overflow
          :field="item.prop"
          v-for="(item, index) in table.column"
          :key="'finally_columns_' + index"
          :title="item.label"/>
        <vxe-column
          show-overflow
          title="创建时间"
          field="create_time"
          width="200"/>
      </vxe-table>
    </div>

    <!--表单增、删、改、查部分-->
    <h5ve-dialog
      :title="crud.form.title + formData.name"
      @close="closeForm"
      :show.sync="crud.visible">
      <crud-form
        v-if="crud.visible"
        ref="closeCrudRef"
        :form="crud.form"
        :dictionary="dict"
        @submit="submitForm"
        @close="crud.visible = false"/>
      <!--        <h5ve-form
                v-if="crud.visible"
                ref="closeCrudRef"
                :options="crud.form.list"
                v-model="crud.form.list"
                :dictionary="dict"
                @submit="submitForm"
                @close="crud.visible = false"
              />-->
    </h5ve-dialog>

    <!--表单导入-->
    <el-dialog
      :width="importForm.errInfo ? '60%' : '500px'"
      :title="'导入-' + formData.name"
      :visible.sync="importForm.visible">
      <import-file
        :form="importForm.form"
        :name="formData.name"
        :show-file-list="false"
        @cancel="importForm.visible = false;"
        @exportTemplate="exportTemplate"
        @close="closeImportForm"
      />
      <error @remove="importForm.errInfo = null;" v-show="importForm.errInfo" :info="importForm.errInfo"/>
    </el-dialog>

    <!--表单导出-->
    <el-dialog
      width="500px"
      :title="'导出-' + formData.name"
      :visible.sync="exportForm.visible">
      <el-form inline size="small">
        <el-form-item label="数据类型">
          <el-select clearable style="width: 100%;" v-model="exportForm.data.dataFrom">
            <el-option value="0" label="导入"></el-option>
            <el-option value="1" label="其他"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item style="text-align: right;">
          <el-button @click="exportForm.visible = false">取 消</el-button>
          <el-button type="primary" @click="exportFormList">导 出</el-button>
        </el-form-item>
      </el-form>
      <!--      <el-alert-->
      <!--        :closable="false"-->
      <!--        title="提示：导出的数据不能大于5000条，15分钟内导出的数据大于2000条的不能超过5次！"-->
      <!--        type="info">-->
      <!--      </el-alert>-->
    </el-dialog>

    <!--高级查询部分-->
    <!--    <el-dialog-->
    <!--      title="高级查询"-->
    <!--      width="900px"-->
    <!--      :close-on-click-modal="false"-->
    <!--      :visible.sync="advancedQueries.visible">-->
    <!--      <advanced-queries-->
    <!--        :dictionary="dict"-->
    <!--        :advanced-queries="advancedQueries"-->
    <!--        :search-list="search.list"-->
    <!--        @save="saveAdvancedQueries"-->
    <!--        @add="addColumn"-->
    <!--        @deleteColumn="deleteColumn"-->
    <!--        @remove="deleteAdvancedQueries"-->
    <!--        @change="advancedQueriesClick"-->
    <!--        @structure="structureAdvancedQueries"-->
    <!--        @cancel="advancedQueries.visible = false"-->
    <!--      />-->
    <!--    </el-dialog>-->
  </div>
</template>

<script>
import {
  dynamicById,
  dynamicFormExport,
  dynamicFormImport,
  dynamicFormImportDownload,
  dynamicList,
  dynamicRemove,
  dynamicSave,
  dynamicUpdate,
  getByCode,
  taskAttributeBatchUpdate
} from "@/api/toolkit/form";

import {getDicts} from "@/api/system/dictData";

import {
  advancedQueriesList,
  deleteQueryLog,
  saveQueryCondition,
  selData
} from "@/api/toolkit/advancedQueries";
import matchList from "./matchList";

import {exportFile} from "./utils";
import CrudForm from "./crud-form";
import ImportFile from "./importFile";
import AdvancedQueries from "./advanced-queries";
import ElTreeSelect from "@/components/TreeSelect/index";
import {getToken} from '@/utils/auth'
import {mapGetters} from 'vuex'
import xlSelect from "./plugin/xl-select";
import xlInput from "./plugin/xl-input";
import xlDate from "./plugin/xl-date";
import xlTime from "./plugin/xl-time";
import xlInputNumber from "./plugin/xl-inputNumber";
import error from "./error/error";

export default {
  name: "Dynamic",
  components: {
    ElTreeSelect,
    ImportFile,
    CrudForm,
    AdvancedQueries,
    xlSelect,
    xlInput,
    xlDate,
    xlTime,
    xlInputNumber,
    error
  },
  provide() {
    return {
      parent: this
    }
  },
  filters: {
    // 兼容原来的图标
    filterIcon(data) {
      const button = ["add-fill", "edit-line", "delete-bin-line", "upload-line", "download-line"];
      const list = ["el-icon-plus", "el-icon-edit", "el-icon-delete", "el-icon-upload2", "el-icon-download"];
      const index = list.indexOf(data);
      return index === -1 ? data : button[index];
    }
  },
  data() {
    return {
      isFullscreen: false,
      selectTypes: ["select", "date", "time", "tree-select"],
      formData: {},
      // 表单用到的字典数据
      // 搜索部分数据
      search: {
        list: [],
        data: {},
        show: true,
        fold: true
      },
      // 高级查询部分数据
      advancedQueries: {
        visible: false,
        matchList: matchList.data,
        list: [],
        structure: {
          name: "",
          code: "",
          type: "0",
          columns: [],
        },
        currentIndex: 0,
      },
      // 导航栏部分数据
      navbar: {
        list: [],
      },
      // 表单列表部分数据
      table: {
        loading: false,
        column: [],
        buttons: [],
        list: [],
        current: 1,
        total: 0,
        size: 200,
      },
      ids: [],
      crud: {
        visible: false,
        addList: [],
        modifyList: [],
        form: {
          title: "",
          batchUpdate: false,
          batchInTurn: false,
          parentId: "",
          type: "",
          readonly: false,
          list: [],
          data: {},
          rules: {},
          table: [],
          childTable: [],
          props: {},
          labelPosition: "top",
          labelWidth: "",
        },
      },
      /*高级查询ID*/
      seniorData: null,
      importForm: {
        visible: false,
        errInfo: null,
        form: {
          data: {},
          action: "",
          headers: {},
          accept: "",
          limit: 1
        }
      },
      exportForm: {
        visible: false,
        data: {
          dataFrom: ""
        }
      },
      trialDialog: false
    }
  },
  computed: {
    ...mapGetters([
      'dict',
      'dictMap',
      'name'
    ]),
    dictTypes() {
      return Object.keys(this.dict)
    },
    tableHeight() {
      let h = 350;
      if (this.isFullscreen) h = 150;
      if (!this.search.show) h -= 50;
      return this.table.list.length ? `calc(100vh - ${h}px)` : "150px";
    },
    searchList() {
      const flag = this.search.fold;
      let list = JSON.parse(JSON.stringify(this.search.list));
      list.forEach(item => {
        item.plugin.placeholder = item.type === 'select' ? ("请输入" + item.label) : item.plugin.placeholder
      })
      list.map((item, index) => {
        item.hide = flag ? index < 2 : true;
        return item;
      })
      return list;
    },
    fieldMap() {
      const list = this.table.column;
      let result = {};
      list.forEach(item => {
        result[item.prop] = item;
      })
      return result;
    }
  },
  methods: {
    selectAllEvent() {
      const records = this.$refs.multipleTable.getCheckboxRecords();
      this.tableSelectionChange(records);
    },
    selectChangeEvent() {
      const records = this.$refs.multipleTable.getCheckboxRecords();
      this.tableSelectionChange(records);
    },
    /**初始化数据*/
    initData() {
      const {path} = this.$route;
      if (path.indexOf('dynamic') === -1) {
        // 不是动态表单不加载
        return;
      }
      const routeStr = path.split("/");
      const code = routeStr[routeStr.length - 1];
      getByCode({code}).then((response) => {
        this.formData = Object.freeze(response.data);
        const btnData = JSON.parse(response.data.btnData);
        let data = JSON.parse(response.data.data);
        let {column} = data;
        let dictTypes = [];
        column = column.map((map) => {
          // 输入提示
          if (this.selectTypes.includes(map.type)) {
            if (!map.plugin.placeholder) {
              map.plugin.placeholder = "请选择" + map.label;
            }
          } else {
            if (!map.plugin.placeholder) {
              map.plugin.placeholder = "请输入" + map.label;
            }
          }
          // 获取字典
          if (map.dictType && !this.dictTypes.includes(map.dictType)) {
            dictTypes.push(map.dictType);
          }
          return map;
        });
        dictTypes = Array.from(new Set(dictTypes));
        const promise = [];
        /**批量请求字典数据*/
        dictTypes.forEach((type) => {
          promise.push(
            new Promise((resolve, reject) => {
              getDicts(type)
                .then((response) => {
                  if (response.data) {
                    console.log(response.data)
                    this.$store.commit("setDict", {
                      name: type,
                      value: Object.freeze(response.data)
                    })
                    resolve(response);
                  }
                }).catch((err) => {
                reject(err);
              });
            })
          );
        });
        /**字典数据请求完成后查询表单数据*/
        Promise.all(promise).then(() => {
          this.responseAfter({
            column,
            btnData,
            data
          })
        })
      })
    },
    /**关闭增删改查表单*/
    closeForm() {
      this.$refs.closeCrudRef.$refs.crudForm.resetFields();
      this.crud.visible = false;
    },
    /**点击试算按钮*/
    trialClick() {
      this.trialDialog = true;
    },
    /**数据初始化后数据处理*/
    responseAfter(params) {
      const {column, btnData, data} = params;
      // 搜索相关
      this.search.list = column.filter((item) => Number(item.isQuery));
      this.search.list.forEach(item => {
        if (item.type === "checkbox") {
          this.search.data[item.prop] = []
        }
        if (item.type === "input" && item.plugin.value || item.type === "textarea" && item.plugin.value) {
          this.$set(this.search.data, item.prop, item.plugin.value)
        }
      })
      Object.freeze(this.search.list);
      // 导航栏按钮相关
      this.navbar.list = btnData.filter(
        (item) => !item.position || item.position === "header"
      );
      this.navbar.list = this.navbar.list.map((map) => {
        map.disabled = ["修改", "删除", "批量交付", "批量修改"].includes(map.name);
        return map;
      });
      Object.freeze(this.navbar.list);
      // 表单列表相关
      this.table.column = Object.freeze(column.filter((item) => Number(item.isList)));
      this.crud.addList = Object.freeze(column.filter((item) => Number(item.isAdd)));
      this.crud.modifyList = Object.freeze(column.filter((item) => Number(item.isEdit)));

      this.crud.form.type = this.formData.type;
      this.crud.form.props = {
        value: "id",
        label: this.formData.treeName,
        children: "childs",
      };
      this.crud.form.childTable = JSON.parse(this.formData.childTable);
      this.crud.form.labelPosition = data.labelPosition;
      this.crud.form.labelWidth = data.labelWidth;
      //this.getAdvancedQueries();
      this.getFormList();
    },
    /**重置搜索部分表单*/
    resetSearch() {
      this.table.current = 1;
      this.search.dataId = null;
      this.resetForm("searchForm");
      this.search.data = {};
      this.search.list.forEach(item => {
        if (item.type === "checkbox") {
          this.$refs.pluginChildcheckbox[0].checkboxList = []
        }
      })
      this.getFormList();
    },
    searchFormList() {
      this.table.current = 1;
      this.getFormList();
      this.search.dataId = null;
    },
    /**确定分页条数*/
    handleSizeChange(val) {
      this.table.size = val;
      this.getFormList();
    },
    /**获取动态表单数据*/
    getFormList() {
      this.table.loading = true;
      dynamicList({
        code: this.formData.code,
        size: this.table.size,
        current: this.table.current,
        type: this.formData.type,
        data: JSON.stringify(this.search.data),
      }).then((response) => {
        const {total, data} = response.data;
        this.table.total = total;
        if (total > 0 && data) {
          this.table.array = JSON.parse(JSON.stringify(data));
          this.table.list = this.formatList(data);
        }
        this.table.loading = false;
      });
    },
    /**格式化列表数据*/
    formatList(list) {
      return list.map(item => {
        const fields = Object.keys(item);
        fields.forEach(prop => {
          if (prop === 'create_time') {
            item[prop] = item[prop] ? this.parseTime(new Date(item[prop]), "{y}-{m}-{d} {h}:{i}:{s}") : "未知";
          }
          if (prop === 'create_by') {
            item[prop] = item[prop] || "未知"
          }
          let attribute = this.fieldMap[prop]
          if (attribute) {
            if (attribute['type'] === 'select') {
              item[prop] = this.dictMap[attribute.dictType + item[prop]] || "——";
            }
            if (attribute['type'] === 'date') {
              item[prop] = item[prop] ? this.parseTime(new Date(item[prop]), "{y}-{m}-{d}") : "——";
            }
            if (attribute['type'] === 'inputNumber') {
              item[prop] = typeof item[prop] === 'number' ? item[prop].toFixed(2) : item[prop];
            }
          }
        })
        return item;
      })
    },
    /**触发动态按钮*/
    handleDynamicButton(data, row) {
      this.crud.form.batchInTurn = false;
      this.crud.form.batchUpdate = false;
      const ids = row ? [row.id] : this.ids;
      this.crud.form.data = {};
      this.crud.form.readonly = false;
      this.crud.form.title = data.name + "-"
      if (["新增"].includes(data.name)) {
        this.crud.form.list = this.crud.addList;
        this.crud.visible = true;
      }
      if (["修改", "编辑", "删除", "批量交付", "批量修改"].includes(data.name)) {
        const list = this.table.list.filter(item => ids.includes(item.id));
        const flag = list.every(item => String(item['create_by']) === String(this.name));
        if (!flag) {
          return this.$notify.warning("只能" + data.name + "自己导入的数据");
        }
      }
      if (["批量交付", "批量修改"].includes(data.name)) {
        this.crud.form.list = this.crud.addList;
        this.crud.visible = true;
      }
      if (["修改", "编辑", "查看", "详情"].includes(data.name)) {
        this.crud.form.list = this.crud.modifyList;
        const id = ids[0];
        dynamicById({
          code: this.formData.code,
          id,
        }).then((response) => {
          this.crud.form.data = JSON.parse(JSON.stringify(response.data));
          this.crud.form.parentId = response.data.parent_id;
          this.crud.visible = true;
        });
      }
      if (["新增", "修改", "编辑", "查看", "详情", "批量交付", "批量修改"].includes(data.name)) {
        this.crud.form = Object.assign(
          this.crud.form,
          JSON.parse(this.formData.data)
        );
        this.crud.form.list.forEach((item) => {
          if (item.validateConfig?.required) {
            const {requiredMessage} = item.validateConfig;
            item.validateConfig.message = requiredMessage || item.label + "必填";
            item.validateConfig.trigger = "blur";
            if (this.selectTypes.includes(item.type)) {
              item.validateConfig.trigger = "change";
            }
            item.validateConfig.pattern = /^[\s\S]*.*[^\s][\s\S]*$/
            this.crud.form.rules[item.prop] = item.validateConfig;
          }
        });
      }
      if (["查看", "详情"].includes(data.name)) {
        this.crud.form.readonly = true;
      }
      if (data.name === "导出") {
        this.exportForm.visible = true;
      }
      if (data.name === "导入") {
        this.importForm.visible = true;
        this.importForm.form = {
          data: {
            code: this.formData.code,
          },
          action: dynamicFormImport(),
          headers: {
            h5ve: getToken(),
          },
          accept: ".xlsx",
          limit: 1,
        };
      }
      if (data.name === "删除") {
        const idStr = ids.join(",");
        this.deleteFormList(idStr);
      }
      if (data.name === '批量交付') {
        this.batchInTurn();
      }
      if (data.name === "批量修改") {
        this.batchUpdate();
      }
    },
    /**批量修改*/
    batchUpdate() {
      this.crud.form.batchUpdate = true;
    },
    /**批量交付*/
    batchInTurn() {
      const oldData = this.table.array.filter(item => this.ids.includes(item.id));
      const flag = oldData.every(item => String(item['rwjfzt0']) === "5");
      if (!flag) {
        return this.$notify.warning("只能提交任务交付状态为：“计划” 的数据！")
      }
      this.crud.form.batchInTurn = true;
    },

    /**删除表单数据列表*/
    deleteFormList(ids) {
      this.$confirm(`确定删除吗？`, "系统提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        dynamicRemove({
          code: this.formData.code,
          id: ids,
        }).then((response) => {
          if (response) {
            this.$notify.success(response['msg'] || "操作成功");
            this.getFormList();
          }
        });
      });
    },

    /**导出表单数据列表*/
    exportFormList() {
      if (this.table.total > 50000) {
        return this.$message.warning("导出的数据不能大于 50000 条！")
      }
      let data = JSON.parse(JSON.stringify(this.search.data));
      data.data_from = this.exportForm.data.dataFrom;
      const params = {
        code: this.formData.code,
        ids: this.ids,
        data: JSON.stringify(data),
        id: this.search.dataId
      }
      if (this.search.dataId) {
        delete params.data;
      }
      exportFile({
        url: dynamicFormExport(),
        suffix: ".xlsx",
        method: "POST",
        params,
        fileName: this.formData.name,
      });
      this.exportForm.visible = false;
    },

    /**表格多选事件*/
    tableSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      const single = selection.length !== 1;
      const multiple = !selection.length;
      this.navbar.list = this.navbar.list.map((map) => {
        if (map.name === "修改") {
          map.disabled = single;
        }
        if (map.name === "删除" || map.name === "批量交付" || map.name === "批量修改") {
          map.disabled = multiple;
        }
        return map;
      });
    },
    submitUpdate() {
      this.crud.form.batchUpdate = false;
      // TODO
    },
    submitBatch(event) {
      const oldData = this.table.array.filter(item => this.ids.includes(item.id));
      let params = {
        oldData,
        ids: this.ids,
        code: this.formData.code,
        taskStatus: event.data['rwjfzt0'],
      };
      taskAttributeBatchUpdate(params).then(response => {
        if (response) {
          this.$notify.success(response['msg'] || "操作成功");
          this.crud.form.batchInTurn = false;
          this.crud.visible = false;
        }
      })
    },
    /**提交动态表单**/
    submitForm(event) {
      const {batchInTurn, batchUpdate} = this.crud.form;
      if (batchInTurn) {
        return this.submitBatch(event);
      }
      if (batchUpdate) {
        return this.submitUpdate(event);
      }
      event.data.parent_id = event.parentId;
      let params = {
        id: event.data.id,
        code: this.formData.code,
        data: JSON.stringify(event.data)
      };
      if (this.ids.length) {
        const oldData = this.table.array.find(item => this.ids.includes(item.id));
        params.oldData = JSON.stringify(oldData);
      }
      const request = event.data.id ? dynamicUpdate(params) : dynamicSave(params);
      request.then(response => {
        if (response) {
          this.$notify.success(response['msg'] || "操作成功");
          this.closeForm();
          this.getFormList();
        }
      })
    },
    /**关闭表单数据导入*/
    closeImportForm(response) {
      this.importForm.errInfo = null;
      if (response && response.code === 0) {
        const {errorInfo} = response.data ? response.data : {};
        if (errorInfo) {
          this.importForm.errInfo = errorInfo;
        } else {
          this.$notify.success(response.msg || "已导入");
          this.getFormList();
          this.importForm.visible = false;
        }
      } else {
        this.$notify.warning(response.msg);
      }
    },
    /**导出模板*/
    exportTemplate() {
      exportFile({
        url: dynamicFormImportDownload(),
        suffix: ".xlsx",
        params: "?code=" + this.formData.code,
        fileName: this.formData.name + "-模板",
      });
    },
    /**高级查询相关方法*/
    advancedQueriesCommand(data) {
      this.table.current = 1;
      this.search.dataId = data;
      //this.advancedQueriesListData(data);
    },
    advancedQueriesListData(data) {
      this.table.loading = true;
      selData({
        size: this.table.size,
        current: this.table.current,
        id: data,
        code: this.formData.code,
      }).then((response) => {
        if (response.data) {
          const {data, total} = response;
          this.table.list = data;
          this.table.total = total || 0;
        }
        this.table.loading = false;
      });
    },
    advancedQueriesClick(index) {
      this.advancedQueries.currentIndex = index;
      const structure = JSON.parse(
        JSON.stringify(
          this.advancedQueries.list[this.advancedQueries.currentIndex]
        )
      );
      const {queryCondition, queryName} = structure;
      structure.columns = JSON.parse(queryCondition);
      structure.name = queryName;
      this.advancedQueries.structure = structure;
    },
    deleteAdvancedQueries() {
      deleteQueryLog({
        id: this.advancedQueries.structure.id,
      }).then((response) => {
        if (response.data) {
          //this.getAdvancedQueries();
        }
      });
    },
    addColumn() {
      this.advancedQueries.structure.columns.push({
        columnName: "",
        queryType: "eq",
        value: "",
      });
    },
    deleteColumn(data) {
      const length = this.advancedQueries.structure.columns.length;
      if (length > 1) {
        this.advancedQueries.structure.columns.splice(data, 1);
      } else {
        this.$message.info("至少保留一个查询条件");
      }
    },
    saveAdvancedQueries() {
      const structure = JSON.parse(
        JSON.stringify(this.advancedQueries.structure)
      );
      structure.code = this.formData.code;
      saveQueryCondition(structure).then((response) => {
        if (response) {
          this.$notify.success("已保存");
          //this.getAdvancedQueries();
        }
      });
    },
    getAdvancedQueries() {
      advancedQueriesList({
        code: this.formData.code,
      }).then((response) => {
        if (response.data) {
          this.advancedQueries.list = response.data;
          if (this.advancedQueries.list.length) {
            const oldIndex = this.advancedQueries.currentIndex;
            const index = this.advancedQueries.list.length - 1;
            this.advancedQueries.currentIndex =
              oldIndex < index ? oldIndex : index;
            const structure = JSON.parse(
              JSON.stringify(
                this.advancedQueries.list[this.advancedQueries.currentIndex]
              )
            );
            const {queryCondition, queryName} = structure;
            structure.columns = JSON.parse(queryCondition);
            structure.name = queryName;
            this.advancedQueries.structure = structure;
          } else {
            const structure = {
              name: "",
              code: "",
              type: "0",
              columns: [],
            };
            this.$set(this.advancedQueries, "structure", structure);
            this.advancedQueries.currentIndex = 0;
          }
        }
      });
    },
    structureAdvancedQueries() {
      const structure = {
        id: "",
        name: "",
        code: "",
        type: "0",
        columns: [
          {
            columnName: "",
            queryType: "eq",
            value: "",
          },
        ],
      };
      this.$nextTick(() => {
        this.$set(this.advancedQueries, "structure", structure);
      });
    },
    /**高级查询相关方法*/
  },
  created() {
    this.initData();
  }
};
</script>

<style lang="scss" scoped>
.dynamic-form-container {
  padding: 15px;
  background-color: #FFFFFF;

  .search-container {
    max-height: 200px;
    overflow-y: auto;
  }
}
</style>

<style>
.nav-container {
  overflow: hidden;
}

.dynamic-form-container *::-webkit-scrollbar {
  width: 15px !important;
  height: 15px !important;
}

.dynamic-form-container *::-webkit-scrollbar-thumb {
  background-color: #d4d5d6 !important;
  border-radius: 2px !important;
}
</style>
